<template>
<call-back />
  <div class="symptom-view">
    <!-- 全局加载组件 -->
    <LoadingOverlay />

    <!-- 顶部固定区域：已选症状和下一步按钮 -->
    <div class="top-fixed-area">
      <!-- 已选症状区域 -->
      <div class="selected-symptoms" v-if="selectedSymptoms.length > 0">
        <h4 class="selected-title">{{ t('selected_symptoms') }}</h4>
        <div class="selected-list">
          <div class="selected-item" v-for="(symptom, index) in selectedSymptoms" :key="index">
            <span class="symptom-name">{{ symptom.name }}</span>
            <button class="remove-btn" @click="removeSymptom(symptom.value)">×</button>
          </div>
        </div>
      </div>

      <!-- 下一步和查询按钮区域 -->
      <div class="next-step-container">
        <button class="next-step-btn" :class="{ 'active': selectedSymptoms.length > 0 }" @click="nextStep">下一步</button>
        <!-- <button class="query-btn" :class="{ 'active': selectedSymptoms.length > 0 }" @click="submitQuery">查询</button> -->
        <span class="next-step-text">{{ t('please_select_symptoms') }}</span>
      </div>
    </div>

    <div class="symptom-container">
      <!-- 搜索区域 -->
      <div class="search-area">
        <div class="custom-input-wrapper no-outline">
          <el-input v-model="searchValue" :placeholder="t('please_input_symptom_keywords')" clearable
            @input="matchSymptoms" class="custom-input no-outline">
            <template #prefix>
              <i class="el-icon-search search-icon"></i>
            </template>
          </el-input>
          <div class="input-hint" v-if="!searchValue">{{ t('input_symptom_keywords') }}</div>
        </div>

        <!-- 搜索结果列表 -->
        <div class="search-results" v-if="showSearchResults && searchResults.length > 0">
          <div class="search-item" v-for="(item, index) in searchResults" :key="index">
            <span class="symptom-name">{{ item.name }}</span>
            <button class="confirm-btn" @click="confirmSymptom(item.value, item.name)">{{ t('confirm') }}</button>
          </div>
        </div>
      </div>

      <!-- 症状分类区域 -->
      <div class="symptom-categories">
        <el-collapse v-model="activeCategories">
          <el-collapse-item v-for="(category, categoryIndex) in getSymptomsList" :key="categoryIndex" :title="category.name"
            :name="categoryIndex.toString()">
            <div class="symptom-buttons">
              <button v-for="(symptom, symptomIndex) in category.child" :key="symptomIndex" class="symptom-btn"
                :class="{ 'selected': isSymptomSelected(symptom.value) }"
                @click="toggleSymptom(symptom.value, symptom.name)">
                {{ symptom.name }}
              </button>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 查询结果区域 -->
      <div class="symptom-result" v-if="showResult">
        <div class="result-header">
          <h4 class="result-title">{{ t('query_result') }}</h4>
          <button class="clear-btn" @click="clearResult">{{ t('clear_result') }}</button>
        </div>
        <div class="result-content">
          {{ symptomResult }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import LoadingOverlay from '@/components/common/LoadingOverlay.vue';
import { ElMessage } from 'element-plus';
import { getSymptoms } from '@/api/symptom';
import { useLoadingStore } from '@/store/loadingStore';
import { useLanguageStore } from '@/store/languageStore';
import CallBack from '@/components/common/CallBack.vue';

const { t } = useLanguageStore();

// 初始化路由
const router = useRouter();

// 定义组件名称
defineOptions({
  name: 'SymptomQuery'
});

// 使用加载状态store
const loadingStore = useLoadingStore();

// 搜索相关

const searchValue = ref('');
const showSearchResults = ref(false);
const searchResults = ref([]);

// 症状相关
const symptoms = ref([]); // 所有症状分类及子项
const selectedSymptoms = ref([]); // 已选症状
const activeCategories = ref(['0']); // 默认展开第一个分类

//根据当前语言获取对应的多语言字段
const getSymptomsList = computed(() => {
  const { getCurrentLang } = useLanguageStore();
  const currentLang = getCurrentLang || 'zh-cn';

  // 使用函数方式获取字段，避免动态属性访问被打包工具优化掉
  const getFieldName = (item, currentLang) => {
    switch(currentLang) {
      case 'zh-cn':
        return item.name_zh_cn || item['name_zh_cn'] || item.name;
      case 'en-us':
        return item.name_en_us || item['name_en_us'] || item.name_zh_cn || item.name;
      case 'ja-jp':
        return item.name_ja_jp || item['name_ja_jp'] || item.name_zh_cn || item.name;
      case 'be-by':
        return item.name_be_by || item['name_be_by'] || item.name_zh_cn || item.name;
      default:
        return item.name_zh_cn || item.name || '未知';
    }
  };

  return symptoms.value.map(item => {
    // 获取分类的对应语言名称
    const categoryName = getFieldName(item, currentLang);

    // 处理子症状
    const translatedChildren = item.child ? item.child.map(child => ({
      ...child,
      name: getFieldName(child, currentLang)
    })) : [];

    return {
      ...item,
      name: categoryName,
      child: translatedChildren
    };
  });
});

// 获取症状分类数据
const fetchSymptoms = async () => {
  try {
    loadingStore.startLoading(t('loading_symptom_data'));

    const response = await getSymptoms();

    if (response.code === 0) {
      symptoms.value = response.data;
    } else {
      throw new Error(response.msg || t('get_symptom_data_failed'));
    }

    loadingStore.endLoading();
  } catch (error) {
    console.error(t('get_symptom_data_failed'), error);
    ElMessage.error(t('get_symptom_data_failed'));
    loadingStore.endLoading();
  }
};

// 搜索匹配症状
const matchSymptoms = () => {
  if (!searchValue.value) {
    showSearchResults.value = false;
    searchResults.value = [];
    return;
  }

  // 搜索所有分类中的症状
  const results = [];
  getSymptomsList.value.forEach(category => {
    category.child.forEach(symptom => {
      if (symptom.name.includes(searchValue.value)) {
        results.push(symptom);
      }
    });
  });

  searchResults.value = results;
  showSearchResults.value = true;
};

// 确认选择搜索结果中的症状
const confirmSymptom = (value, name) => {
  toggleSymptom(value, name);
  searchValue.value = '';
  showSearchResults.value = false;
};

// 判断症状是否已选中
const isSymptomSelected = (value) => {
  return selectedSymptoms.value.some(item => item.value === value);
};

// 切换症状选中状态
const toggleSymptom = (value, name) => {
  const index = selectedSymptoms.value.findIndex(item => item.value === value);

  if (index > -1) {
    // 如果已选中，则移除
    selectedSymptoms.value.splice(index, 1);
  } else {
    // 如果未选中，则添加，但限制最多5个
    if (selectedSymptoms.value.length >= 8) {
      ElMessage.warning(t('max_symptom_limit'));
      return;
    }
    selectedSymptoms.value.push({ value, name });
  }
};

// 移除选中的症状
const removeSymptom = (value) => {
  const index = selectedSymptoms.value.findIndex(item => item.value === value);
  if (index > -1) {
    selectedSymptoms.value.splice(index, 1);
  }
};

// 查询结果相关
const showResult = ref(false);
const symptomResult = ref('');

// 清除查询结果
const clearResult = () => {
  showResult.value = false;
  symptomResult.value = '';
};

// 下一步操作
const nextStep = () => {
  if (selectedSymptoms.value.length === 0) {
    ElMessage.warning(t('please_select_symptoms'));
    return;
  }

  if (selectedSymptoms.value.length > 8) {
    ElMessage.warning(t('max_symptom_limit'));
    return;
  }

  // 保存选中的症状到本地存储
  const symptomValues = selectedSymptoms.value.map(symptom => symptom.value);

  // 保存完整的症状对象（包含所有语言字段）用于第二页显示
  const fullSymptomData = selectedSymptoms.value.map(symptom => {
    // 在症状列表中找到对应的完整数据
    for (const category of symptoms.value) {
      for (const child of category.child || []) {
        if (child.value === symptom.value) {
          return child; // 返回包含所有语言字段的完整数据
        }
      }
    }
    return symptom; // 如果找不到，返回原数据
  });

  localStorage.setItem('chooseTxt', JSON.stringify(symptomValues));
  localStorage.setItem('selectedSymptomData', JSON.stringify(fullSymptomData));

  // 跳转到下一步页面
  router.push('/symptom-second');
};

onMounted(() => {
  fetchSymptoms();
});
</script>

<style lang="less" scoped>
* {
  outline: none !important;
}

.no-outline {
  outline: none !important;
  border: none !important;
}

.symptom-view {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  position: relative;
  background-color: #f8f9fc;
}

.symptom-container {
  flex: 1;
  padding: 20px;
  max-width: 850px;
  margin: 0 auto 30px;
  width: 100%;
  background-color: #fff;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  outline: none;
  border: none;
  margin-top: 0;
}

.section-title {
  text-align: center;
  margin-bottom: 25px;
  color: #333;
  font-weight: 600;
  position: relative;
  padding-bottom: 12px;
}

.section-title:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  border-radius: 3px;
}

/* 顶部固定区域 */
.top-fixed-area {
  position: sticky;
  top: 70px;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0 2px 15px rgba(63, 81, 181, 0.12);
  margin-bottom: 20px;
  border-radius: 0 0 10px 10px;
}

/* 下一步按钮区域 */
.next-step-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  border-radius: 0 0 10px 10px;
}

.next-step-btn {
  padding: 10px 24px;
  background-color: #e0e0e0;
  color: #666;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
}

.next-step-btn.active {
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  color: white;
  box-shadow: 0 4px 10px rgba(63, 81, 181, 0.3);
}

.next-step-text {
  font-size: 15px;
  color: #555;
  font-weight: 500;
}

/* 搜索区域 */
.search-area {
  margin-bottom: 25px;
  position: relative;
  max-width: 100%;
  width: 100%;
  outline: none;
}

.custom-input-wrapper {
  margin-bottom: 10px;
  position: relative;
  width: 100%;
  max-width: 100%;
  outline: none;
  border: none;
}

.input-hint {
  position: absolute;
  bottom: -22px;
  left: 10px;
  font-size: 12px;
  color: #9fa8da;
  opacity: 0.8;
  transition: opacity 0.3s ease;
}

.input-hint:hover {
  opacity: 1;
}

.custom-input {
  width: 100%;
  max-width: 100%;
  outline: none !important;

  :deep(.el-input__wrapper) {
    box-shadow: none !important;
    outline: none !important;
    border: none !important;
  }

  :deep(.el-input__inner) {
    border-radius: 20px;
    border: 2px solid #e0e4f6;
    padding: 12px 20px;
    font-size: 15px;
    color: #424770;
    background-color: #f8f9ff;
    box-shadow: 0 3px 10px rgba(92, 107, 192, 0.08);
    transition: all 0.3s ease;
    height: 48px;
    outline: none !important;

    &:focus {
      border-color: #5c6bc0;
      background-color: #ffffff;
      box-shadow: 0 4px 12px rgba(92, 107, 192, 0.15);
      outline: none !important;
    }

    &::placeholder {
      color: #9fa8da;
      font-weight: 400;
    }
  }

  :deep(.el-input__prefix) {
    left: 12px;
  }

  :deep(.search-icon) {
    color: #5c6bc0;
    font-size: 18px;
  }

  &.no-outline {
    outline: none !important;
    border: none !important;
  }
}

.search-results {
  position: absolute;
  top: calc(100% + 5px);
  left: 0;
  width: 100%;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(92, 107, 192, 0.22);
  z-index: 10;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid rgba(92, 107, 192, 0.1);
  animation: fadeIn 0.2s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.search-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 18px;
  border-bottom: 1px solid #eef0f7;
  transition: all 0.2s ease;
}

.search-item:hover {
  background-color: #f0f3ff;
  transform: translateX(3px);
}

.search-item:last-child {
  border-bottom: none;
}

.symptom-name {
  font-size: 15px;
}

.confirm-btn {
  padding: 6px 14px;
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(63, 81, 181, 0.2);
  transition: all 0.3s ease;
}

.confirm-btn:hover {
  box-shadow: 0 4px 10px rgba(63, 81, 181, 0.3);
  transform: translateY(-2px);
}

/* 症状分类区域 */
.symptom-categories {
  margin-bottom: 25px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 3px 15px rgba(63, 81, 181, 0.1);
  overflow: hidden;
}

:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  background: linear-gradient(to right, #f5f7ff, #fff);
  font-size: 16px;
  font-weight: 500;
  color: #333;
  padding: 15px 20px;
  border-bottom: 1px solid #eef0f7;
  position: relative;

  &:hover {
    background: linear-gradient(to right, #eef1ff, #f8f9ff);
  }

  &:before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 60%;
    background: linear-gradient(135deg, #3f51b5, #5c6bc0);
    border-radius: 0 2px 2px 0;
  }
}

:deep(.el-collapse-item__content) {
  padding: 15px 20px;
}

.symptom-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 5px 0;
}

.symptom-btn {
  padding: 8px 16px;
  background-color: #f5f7ff;
  border: 1px solid #dde1f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  color: #444;
  box-shadow: 0 1px 3px rgba(63, 81, 181, 0.08);
}

.symptom-btn:hover {
  background-color: #e8f0ff;
  border-color: #c0cde6;
  transform: translateY(-2px);
  box-shadow: 0 3px 8px rgba(63, 81, 181, 0.15);
  color: #3f51b5;
}

.symptom-btn.selected {
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  color: white;
  border-color: #3f51b5;
  box-shadow: 0 3px 8px rgba(63, 81, 181, 0.25);
}

/* 已选症状区域 */
.selected-symptoms {
  background-color: #f0f3ff;
  border-radius: 10px;
  padding: 20px;
  margin-top: 20px;
  box-shadow: 0 3px 15px rgba(63, 81, 181, 0.12);
  border: 1px solid rgba(63, 81, 181, 0.1);
}

.selected-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.selected-title:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 50px;
  height: 3px;
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  border-radius: 3px;
}

.selected-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.selected-item {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #3f51b5, #5c6bc0);
  color: white;
  padding: 8px 14px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 3px 8px rgba(63, 81, 181, 0.2);
  transition: all 0.3s ease;
}

.selected-item:hover {
  box-shadow: 0 5px 12px rgba(63, 81, 181, 0.3);
  transform: translateY(-2px);
}

.remove-btn {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 18px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s ease;
}

.remove-btn:hover {
  transform: scale(1.2);
}

/* 查询结果区域样式 */
.symptom-result {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.result-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.clear-btn {
  background-color: #f56c6c;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.clear-btn:hover {
  background-color: #e74c3c;
}

.next-step-btn,
.query-btn {
  width: 120px;
  height: 40px;
  border-radius: 20px;
  background-color: #e0e0e0;
  color: #999;
  font-size: 16px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 10px;
}

.next-step-btn.active {
  background-color: #4a7eff;
  color: white;
}

.query-btn.active {
  background-color: #5cb85c;
  color: white;
}

.result-content {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  white-space: pre-wrap;
  min-height: 100px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .symptom-container {
    padding: 15px;
    margin-bottom: 20px;
  }

  .top-fixed-area {
    border-radius: 0;
    top: 60px;
  }

  .next-step-container {
    padding: 12px 15px;
    border-radius: 0;
  }

  .selected-symptoms {
    padding: 15px;
  }

  .next-step-btn {
    padding: 8px 16px;
    font-size: 15px;
  }

  .next-step-text {
    font-size: 14px;
  }

  .symptom-buttons {
    gap: 10px;
  }

  .symptom-btn {
    padding: 7px 14px;
    font-size: 13px;
  }

  :deep(.el-collapse-item__header) {
    font-size: 15px;
    padding: 12px 15px;
  }

  .selected-title {
    font-size: 16px;
  }
}

@media (max-width: 480px) {
  .symptom-container {
    padding: 12px;
  }

  .next-step-container {
    padding: 10px 12px;
  }

  .selected-symptoms {
    padding: 12px;
  }

  .next-step-btn {
    padding: 7px 14px;
    font-size: 14px;
  }

  .next-step-text {
    font-size: 13px;
  }

  .symptom-buttons {
    gap: 8px;
  }

  .symptom-btn {
    padding: 6px 12px;
    font-size: 12px;
  }

  .selected-item {
    padding: 6px 12px;
    font-size: 13px;
  }
}
</style>